<?php

/**
 * 网站栏目模型
 * File Name：CategoryModel.php
 * File Encoding：UTF-8
 * File New Time：2014-5-6 9:10:30
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class CategoryModel extends BaseModel {

    private $cacheCategorysAll = NULL;

    public function tableName() {
        return '{{category}}';
    }

    public function rules() {
        return array(
            //添加栏目场景
            array('cat_name', 'required', 'on' => 'add', 'message' => '请填写栏目名！'),
            array('cat_name', 'unique', 'allowEmpty' => false, 'on' => 'add', 'message' => '该栏目名已经存在！'),
            //编辑场景
            array('cat_name', 'required', 'on' => 'editor', 'message' => '请填写栏目名！'),
            array('cat_name', 'unique', 'allowEmpty' => false, 'on' => 'editor', 'message' => '该栏目名已经存在！'),
            array('quantify', 'numerical', 'allowEmpty' => true, 'integerOnly' => true),
            array('single_quantity', 'numerical', 'allowEmpty' => true),
            //安全的。。。
            array('moduleid,level,is_hot,is_new,is_best,status,cat_img,class_name,parentid,listorder,cat_des,is_app', 'safe'),
        );
    }

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    //数据保存后回调
    protected function afterSave() {
        parent::afterSave();
        //更新缓存
        $this->saveCateCache();
    }

    //数据删除后回调
    protected function afterDelete() {
        parent::afterDelete();
        //更新缓存
        $this->saveCateCache();
    }

    /**
     * 更新栏目缓存
     * @param type $cat_id 栏目id
     */
    public function saveCateCache($cat_id = 0) {
        if (isset($this->cat_id) && $this->cat_id) {
            $this->getCategory($this->cat_id, '', true);
            //echo $this->cat_id;exit;
        } else if ($cat_id) {
            $this->getCategory($cat_id, '', true);
        }
        $this->getList(false);
        $this->getCatMenu(false);
    }

    /**
     * 获取Level数据
     * @param type $str 如果是字符串，获取对应键值，如果是数字，获取名称，为空，获取全部(数组)
     * @return string
     */
    public function getLevelTags($str = NULL) {
        $list = array(0 => '普通分类', 1 => '首页主导航', 2 => '推荐分类');
        if ($str === NULL) {
            return $list;
        } else {
            if (is_string($str)) {//传入字符，表示返回id
                return array_search($str, $list);
            } else {
                return isset($list[$str]) ? $list[$str] : false;
            }
        }
        return array();
    }

    /**
     * 用于模板页面显示<select>这里</select>使用
     * @return string <option value='xx'>xxx</option>
     */
    public function htmlCategorySelectOption($parentid = 0) {
        $tree = new Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $str = "<option value='\$cat_id' \$selected>\$spacer \$cat_name</option>";
        $array = $this->getList();
        $tree->init($array);
        return $tree->get_tree(0, $str, $parentid);
    }

    /**
     * 获取子栏目ID列表
     * @param type $catid 栏目id
     * @return string 返回栏目子列表，以逗号隔开
     */
    public function getArrChildid($catid) {
        //栏目数据
        if (!$this->cacheCategorysAll) {
            $this->cacheCategorysAll = $this->getList();
        }
        $arrchildid = $catid;
        if (is_array($this->cacheCategorysAll)) {
            foreach ($this->cacheCategorysAll as $id => $cat) {
                if ($cat['parentid'] && $id != $catid && $cat['parentid'] == $catid) {
                    $arrchildid .= ',' . $this->getArrChildid($id);
                }
            }
        }
        return $arrchildid;
    }

    /**
     * 使用递归的方式，获取全部的父栏目id列表
     * @param type $catid 栏目ID
     * @param type $arrparentid 父目录ID
     * @param type $n 查找的层次
     * @return string 返回父栏目id列表，以逗号隔开
     */
    public function getArrParentid($catid, $arrparentid = '', $n = 1) {
        //栏目数据
        if (empty($this->cacheCategorysAll)) {
            $this->cacheCategorysAll = $this->getList();
        }
        if ($n > 10 || !is_array($this->cacheCategorysAll) || !isset($this->cacheCategorysAll[$catid])) {
            return false;
        }
        //获取当前栏目的上级栏目ID
        $parentid = $this->cacheCategorysAll[$catid]['parentid'];
        //所有父ID
        $arrparentid = $arrparentid ? $parentid . ',' . $arrparentid : $parentid;
        if ($parentid) {
            $arrparentid = $this->getArrParentid($parentid, $arrparentid, ++$n);
        } else {
            $this->cacheCategorysAll[$catid]['arrparentid'] = $arrparentid;
        }
        return $arrparentid;
    }

    /**
     * 获取单条栏目数据
     * @param type $catid 栏目Id
     * @param type $field 字段
     * @param type $newCache 是否刷新缓存
     * @return boolean 失败falsh，成功返回数组或者字段值
     */
    public function getCategory($catid, $field = '', $newCache = false) {
        if (empty($catid)) {
            return false;
        }
        //缓存key
        $key = "CategoryModel_getCategory_{$catid}";
        //清理缓存
        if ($newCache) {
            Yii::app()->cache->delete($key);
        }
        //读取缓存
        $cache = Yii::app()->cache->get($key);
        //检查缓存是否存在，不存在创建
        if (empty($cache)) {
            $category = $this->findByPk($catid);
            if (empty($category)) {
                return false;
            }
            $cache = $category->attributes;
            //默认缓存3600秒
            Yii::app()->cache->set($key, $cache, 3600);
        }
        if ($field) {
            //支持var.property，不过只支持一维数组
            if (false !== strpos($field, '.')) {
                $vars = explode('.', $field);
                return $cache[$vars[0]][$vars[1]];
            } else {
                return $cache[$field];
            }
        } else {
            return $cache;
        }
    }

    /**
     * 获取全部栏目数据
     * @param type $newCache 是否使用缓存，默认使用
     * @return array 数据集合
     */
    public function getList($newCache = true) {
        //缓存key
        $key = "CategoryModel_getList";
        if (!$newCache) {
            Yii::app()->cache->delete($key);
        }
        //读取缓存
        $cache = Yii::app()->cache->get($key);
        if (empty($cache)) {
            $model = $this->findAll($this->where(array('status' => 1, 'order' => 'listorder ASC')));
            $categorys = array();
            if (empty($model)) {
                return $categorys;
            }
            foreach ($model as $obj) {
                $info = $obj->attributes;
                if (!empty($info)) {
                    $info['catid'] = $info['cat_id'];
                    $categorys[$info['cat_id']] = $info;
                }
            }
            $cache = $categorys;
            //默认缓存3600秒
            Yii::app()->cache->set($key, $cache, 3600);
        }
        return $cache;
    }

    /**
     * 获取全部栏目列表 一维数组
     * @return array
     */
    public function getListArray() {
        $list = $this->getList();
        $data = array();
        foreach ($list as $rs) {
            $data[$rs['cat_id']] = $rs['cat_name'];
        }
        return $data;
    }

    public function getCatMenu($cache = true) {
        $key = "CategoryModel_getCatMenu";
        if ($cache) {
            Yii::app()->cache->delete($key);
        }
        $return = Yii::app()->cache->get($key);
        if ($return) {
            return $return;
        }

        $cats = $this->findAll('level > :level', array(':level' => 0));
        $return = array();
        if ($cats) {
            foreach ($cats as $cat) {
                $return[] = array(
                    'label' => $cat->cat_name,
                    'url' => array('/front/index/index/', 'cid' => $cat->cat_id),
                    'itemOptions' => array('class' => $cat->class_name),
                );
            }
        }
        Yii::app()->cache->set($key, $return);
        return $return;
    }

    /**
     * 根据栏目ID删除
     * @param type $catid 栏目ID
     * @return type
     */
    public function deleteCategoryByPk($catid) {
        if (empty($catid)) {
            return $catid;
        }
        $model = $this->findByPk($catid);
        if (empty($model)) {
            return false;
        }
        $info = $model->attributes;
        //检查是否有子栏目
        $childid = $this->getArrChildid($info['cat_id']);
        if (empty($childid)) {
            return $model->delete();
        }
        return $this->deleteAll($this->where(array('cat_id' => array('IN', $childid))));
    }

    /**
     * 根据栏目ID获取moduleid
     * @param type $catid
     * @return type
     */
    public function getModuleId($catid) {
        return $this->getCategory($catid, 'moduleid');
    }

    public static function getCat_nameForCount($arrData){
        if(!$arrData){
            return false;
        }
        $arrReturn = array();
        foreach($arrData as $cat_id => $count){
            $objModel = self::model()->findByPk($cat_id);
            $arrReturn[] = "{$objModel->cat_name}:<a href='javascript:void(0)' data-cat_id='{$cat_id}'>$count</a>";
        }
        return implode('<br/>', $arrReturn);
    }

}
